package org.example.ding.controller;

import org.example.ding.model.NutritionAlert;
import org.example.ding.service.CustomUserDetailsService;
import org.example.ding.service.NutritionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 营养预警控制器
 */
@Controller
@RequestMapping("/alerts")
public class AlertController {

    @Autowired
    private NutritionService nutritionService;

    /**
     * 预警中心页面
     */
    @GetMapping
    public String alertCenter(@AuthenticationPrincipal CustomUserDetailsService.CustomUserPrincipal principal,
                             Model model) {
        
        Long userId = principal.getId();
        LocalDate today = LocalDate.now();
        
        // 获取今日预警
        NutritionAlert todayAlert = nutritionService.checkNutritionAlert(userId, today);
        
        // 获取最近7天的预警历史
        List<NutritionAlert> alertHistory = new java.util.ArrayList<>();
        for (int i = 1; i <= 7; i++) {
            LocalDate date = today.minusDays(i);
            NutritionAlert alert = nutritionService.checkNutritionAlert(userId, date);
            if (alert.hasAlerts()) {
                alertHistory.add(alert);
            }
        }
        
        model.addAttribute("todayAlert", todayAlert);
        model.addAttribute("alertHistory", alertHistory);
        model.addAttribute("today", today);
        
        return "alerts/center";
    }

    /**
     * 获取当前预警信息的API
     */
    @GetMapping("/api/current")
    public ResponseEntity<Map<String, Object>> getCurrentAlerts(
            @AuthenticationPrincipal CustomUserDetailsService.CustomUserPrincipal principal) {
        
        Long userId = principal.getId();
        LocalDate today = LocalDate.now();
        
        NutritionAlert todayAlert = nutritionService.checkNutritionAlert(userId, today);
        
        Map<String, Object> response = new HashMap<>();
        response.put("alertCount", todayAlert.getTotalAlertCount());
        response.put("highPriorityCount", todayAlert.getHighPriorityCount());
        response.put("mediumPriorityCount", todayAlert.getMediumPriorityCount());
        response.put("lowPriorityCount", todayAlert.getLowPriorityCount());
        response.put("date", today.toString());
        
        return ResponseEntity.ok(response);
    }

    /**
     * 获取预警统计数据的API
     */
    @GetMapping("/api/statistics")
    public ResponseEntity<Map<String, Object>> getAlertStatistics(
            @AuthenticationPrincipal CustomUserDetailsService.CustomUserPrincipal principal,
            @RequestParam(defaultValue = "7") int days) {
        
        Long userId = principal.getId();
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(days - 1);
        
        Map<String, Integer> statistics = new HashMap<>();
        statistics.put("high", 0);
        statistics.put("medium", 0);
        statistics.put("low", 0);
        
        for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
            NutritionAlert alert = nutritionService.checkNutritionAlert(userId, date);
            statistics.put("high", statistics.get("high") + alert.getHighPriorityCount());
            statistics.put("medium", statistics.get("medium") + alert.getMediumPriorityCount());
            statistics.put("low", statistics.get("low") + alert.getLowPriorityCount());
        }
        
        Map<String, Object> response = new HashMap<>();
        response.put("statistics", statistics);
        response.put("period", days + "天");
        response.put("startDate", startDate.toString());
        response.put("endDate", endDate.toString());
        
        return ResponseEntity.ok(response);
    }

    /**
     * 获取预警趋势数据的API
     */
    @GetMapping("/api/trend")
    public ResponseEntity<Map<String, Object>> getAlertTrend(
            @AuthenticationPrincipal CustomUserDetailsService.CustomUserPrincipal principal,
            @RequestParam(defaultValue = "30") int days) {
        
        Long userId = principal.getId();
        LocalDate endDate = LocalDate.now();
        LocalDate startDate = endDate.minusDays(days - 1);
        
        List<Map<String, Object>> trendData = new java.util.ArrayList<>();
        
        for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
            NutritionAlert alert = nutritionService.checkNutritionAlert(userId, date);
            
            Map<String, Object> dayData = new HashMap<>();
            dayData.put("date", date.toString());
            dayData.put("total", alert.getTotalAlertCount());
            dayData.put("high", alert.getHighPriorityCount());
            dayData.put("medium", alert.getMediumPriorityCount());
            dayData.put("low", alert.getLowPriorityCount());
            
            trendData.add(dayData);
        }
        
        Map<String, Object> response = new HashMap<>();
        response.put("trendData", trendData);
        response.put("startDate", startDate.toString());
        response.put("endDate", endDate.toString());
        
        return ResponseEntity.ok(response);
    }

    /**
     * 预警详情页面
     */
    @GetMapping("/detail")
    public String alertDetail(@AuthenticationPrincipal CustomUserDetailsService.CustomUserPrincipal principal,
                             @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date,
                             Model model) {
        
        Long userId = principal.getId();
        NutritionAlert alert = nutritionService.checkNutritionAlert(userId, date);
        
        model.addAttribute("alert", alert);
        model.addAttribute("date", date);
        model.addAttribute("isToday", date.equals(LocalDate.now()));
        
        return "alerts/detail";
    }

    /**
     * 预警设置页面
     */
    @GetMapping("/settings")
    public String alertSettings(@AuthenticationPrincipal CustomUserDetailsService.CustomUserPrincipal principal,
                               Model model) {
        
        // 这里可以添加预警阈值设置功能
        // 目前使用默认的预警规则
        
        return "alerts/settings";
    }
}
